<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 卡片头部 -->
      <div class="login-header">
        <div class="login-header-content mb-8">
            <div class="logo-section">
              <div class="logo-container">
                <el-icon class="logo-icon"><Ship /></el-icon>
              </div>
            </div>
            <div class="title-section">
              <h2 class="welcome-title">C-Plate全幅画印字划线系统</h2>
              <p class="welcome-subtitle">智能印字，精准划线</p>
            </div>
          </div>


        <!-- 登录表单 -->
        <el-form
          :model="form"
          label-position="top"
          @submit.prevent="handleLogin"
          class="login-form"
        >
          <!-- 用户名/邮箱字段 -->
          <el-form-item
            label="用户名或邮箱"
            :error="errors.username"
            prop="username"
          >
            <el-input
              v-model="form.username"
              placeholder="请输入用户名或邮箱"
              @blur="validateField('username')"
              prefix-icon="User"
              :validate-event="false"
            />
          </el-form-item>

          <!-- 密码字段 -->
          <el-form-item
            label="密码"
            :error="errors.password"
            prop="password"
          >
            <el-input
              v-model="form.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              @input="checkPasswordStrength"
              @blur="validateField('password')"
              @keyup.enter="handleLogin"
              prefix-icon="Lock"
              :validate-event="false"
              show-password
            />
          </el-form-item>

        <!-- 错误提示 -->
        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          show-icon
          :closable="false"
          class="mb-4"
        />
          <!-- 密码强度指示器 -->
          <div v-if="form.password.length > 0" class="password-strength">
            <div class="strength-header">
              <span class="strength-label">密码强度</span>
              <span :class="getStrengthClass()">
                {{ getStrengthText() }}
              </span>
            </div>
            <div class="strength-bar-container">
              <div 
                :class="getStrengthBarClass()" 
                class="strength-bar"
                :style="{ width: getStrengthPercentage() }"
              ></div>
            </div>
          </div>

          <!-- 记住我 -->
          <el-form-item class="remember-container">
            <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              @click="handleLogin"
              :loading="isSubmitting"
              class="login-button"
              full-width
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 卡片底部 -->
      <div class="login-footer">
        <p> 中船数字信息技术有限公司 © {{ new Date().getFullYear() }} 版权所有</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { Ship, User, Lock, Loading } from '@element-plus/icons-vue';
import apiClient, { fetchUserInfo, login, TOKEN_STORAGE_KEY, USER_NAME_STORAGE_KEY } from '../api/auth.service';

// 定义表单类型
interface LoginForm {
  username: string;
  password: string;
  rememberMe: boolean;
}

// 定义错误类型
interface LoginErrors {
  username: string | null;
  password: string | null;
}

// 表单数据
const form = reactive<LoginForm>({
  username: '',
  password: '',
  rememberMe: false
});

// 错误信息
const errors = reactive<LoginErrors>({
  username: null,
  password: null
});

// 状态变量
const showPassword = ref(false);
const isSubmitting = ref(false);
const errorMessage = ref<string | null>(null);
const passwordStrength = ref<number>(0); // 0: 空, 1: 弱, 2: 中, 3: 强, 4: 非常强

const router = useRouter();

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 验证单个字段
const validateField = (field: keyof LoginForm) => {
  switch (field) {
    case 'username':
      if (!form.username.trim()) {
        errors.username = '请输入用户名或邮箱';
      } else {
        errors.username = null;
      }
      break;
    case 'password':
      if (!form.password) {
        errors.password = '请输入密码';
      } else {
        errors.password = null;
      }
      break;
  }
};

// 验证整个表单
const validateForm = (): boolean => {
  let isValid = true;
  
  if (!form.username.trim()) {
    errors.username = '请输入用户名或邮箱';
    isValid = false;
  } else {
    errors.username = null;
  }
  
  if (!form.password) {
    errors.password = '请输入密码';
    isValid = false;
  } else {
    errors.password = null;
  }
  
  return isValid;
};

// 检查密码强度
const checkPasswordStrength = () => {
  const password = form.password;
  
  if (!password) {
    passwordStrength.value = 0;
    return;
  }
  
  // 简单的密码强度检测逻辑
  let strength = 0;
  
  // 长度检测
  if (password.length >= 8) strength++;
  if (password.length >= 12) strength++;
  
  // 复杂度检测
  if (/[A-Z]/.test(password)) strength++; // 包含大写字母
  if (/[0-9]/.test(password)) strength++; // 包含数字
  if (/[^A-Za-z0-9]/.test(password)) strength++; // 包含特殊字符
  
  // 限制强度为1-4
  passwordStrength.value = Math.min(strength, 4);
};

// 获取密码强度文本
const getStrengthText = (): string => {
  switch (passwordStrength.value) {
    case 0: return '空';
    case 1: return '弱';
    case 2: return '中';
    case 3: return '强';
    case 4: return '非常强';
    default: return '空';
  }
};

// 获取密码强度文本颜色类
const getStrengthClass = (): string => {
  switch (passwordStrength.value) {
    case 0: return '';
    case 1: return 'strength-weak';
    case 2: return 'strength-medium';
    case 3: return 'strength-strong';
    case 4: return 'strength-very-strong';
    default: return '';
  }
};

// 获取密码强度条颜色类
const getStrengthBarClass = (): string => {
  switch (passwordStrength.value) {
    case 0: return '';
    case 1: return 'strength-bar-weak';
    case 2: return 'strength-bar-medium';
    case 3: return 'strength-bar-strong';
    case 4: return 'strength-bar-very-strong';
    default: return '';
  }
};

// 获取密码强度百分比
const getStrengthPercentage = (): string => {
  switch (passwordStrength.value) {
    case 0: return '0%';
    case 1: return '25%';
    case 2: return '50%';
    case 3: return '75%';
    case 4: return '100%';
    default: return '0%';
  }
};

// 处理登录
const handleLogin = async () => {
  try {
    // 重置错误信息
    errorMessage.value = null;
    
    // 表单验证
    if (!validateForm()) {
      return;
    }
    
    // 设置提交状态
    isSubmitting.value = true;
    
    // 使用auth.service中的login函数进行登录
    const isSuccess = await login(form.username, form.password);
  
    if (isSuccess) {
      // 检查 window.chrome.webview.postMessage 是否存在
      // (使用可选链操作符 ?. 来安全地访问)
      if (window.chrome?.webview?.postMessage) {
        //在 WebView2 中: 发送消息通知 WPF 宿主
        console.log('在 WebView2 中检测到登录成功，正在通知 WPF 宿主...');        
        const user = await fetchUserInfo();
        // 发送一个 JSON 对象，WPF 端可以解析
        window.chrome.webview.postMessage({
          type: 'LoginSuccess',
          accessToken: localStorage.getItem(TOKEN_STORAGE_KEY),
          user: user 
        });
      } else {
        console.log('在浏览器中检测到登录成功，正在跳转页面...');
        // 登录成功，重定向到首页
        router.push('/');
      }
    } else {
      // 登录失败，显示错误信息
      errorMessage.value = '用户名或密码不正确，请重试';
    }
    
  } catch (error: any) {
    errorMessage.value = '登录过程中发生错误，请稍后再试';
    console.error('登录错误:', error);
  } finally {
    // 重置提交状态
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 自定义样式 */
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom right, #f0f9ff, #e0f2fe);
  padding: 0;
  margin: 0;
}

.login-card {
  width: 100%;
  max-width: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.login-header {
  padding: 30px;
}

.login-header-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.logo-section {
  display: flex;
  justify-content: flex-start;
}

.logo-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 72px;
  height: 72px;
  background: linear-gradient(135deg, #1976d2, #1565c0);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3);
  transition: all 0.3s ease;
}

.logo-container:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(25, 118, 210, 0.4);
}

.logo-icon {
  color: white;
  font-size: 36px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.title-section {
  max-width: 100%;
  text-align: left;
}

.welcome-title {
  font-size: 22px;
  font-weight: 700;
  color: #1976d2;
  margin-bottom: 12px;
  line-height: 1.4;
  letter-spacing: 0.5px;
}

.welcome-subtitle {
  color: #aaa;
  font-size: 14px;
  font-weight: 500;
  margin: 0;
  opacity: 0.9;
}

.login-form {
  margin-top: 20px;
}

.el-form-item__label {
  font-size: 14px;
  font-weight: 500;
  color: #555;
  margin-bottom: 8px;
}

.password-strength {
  margin-top: 12px;
}

.strength-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
}

.strength-label {
  color: #666;
}

.strength-bar-container {
  width: 100%;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.strength-bar {
  height: 100%;
  transition: width 0.3s ease;
}

.remember-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

.login-footer {
  background-color: #fafafa;
  padding: 16px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
  font-size: 14px;
  color: #666;
}

/* 密码强度样式 */
.strength-weak {
  color: #e53935;
}

.strength-medium {
  color: #f9a825;
}

.strength-strong {
  color: #1976d2;
}

.strength-very-strong {
  color: #388e3c;
}

.strength-bar-weak {
  background-color: #e53935;
}

.strength-bar-medium {
  background-color: #f9a825;
}

.strength-bar-strong {
  background-color: #1976d2;
}

.strength-bar-very-strong {
  background-color: #388e3c;
}
</style>
